const word = document.getElementById('word');
const text = document.getElementById('text');
const scareE1 = document.getElementById('score');
const timeE1 = document.getElementById('time');
const endgameE1 =document.getElementById
('end-game-container');
const settingBtn = document.getElementById('settings-btn');
const settings = document.getElementById('settings');
const settingsForm = document.getElementById
('settings-form');
const difficultySelect = document.getElementById
('difficulty');

// 单词列表
const words = [
'const',
'let',
'input',
'image',
'form',
'style',
'display',
'container',
'element',
'class',
'document',
'background',
'transition',
'transform',
'translate',
'border',
'radius',
'margin',
'padding',
'select'
];

//初始化单词
let randomWords;

//初始化分数
let score = 0;

//初始化时间
let time = 10;

//设置难度指为LS中的指或者中等难度
let difficulty = localStorage.getItem('difficulty') | 
null ? localStorage.getItem('difficulty') : 'medium';

// 将难度指输出到下拉选项框中
difficultySelect.value = difficulty;

//开始时聚焦到输入框
text.focus();

// 时间开始倒数
const timeInterval = setInterval(updateTime, 1000);

//从数组中获得随机单词
function getRandomWord() {
    return words[Math.floor(Math.random() * words.length)];
}

//更新分数
function updateScore() {
    score++;
    scareE1.innerHTML = score;
}

//更新时间
function updateTime() {
    time--;
    timeE1.innerHTML = time + 's'

    if (time === 0) {
        clearInterval(timeInterval);
        // 结束游戏
        gameOver();
    }
}

//结束游戏，展示结束游戏界面
function gameOver() {
    endgameE1.innerHTML = `
    <h1>时间结束了</h1>
    <p>你的最终最终的分数是吼${score}</p>
    <button onClick="location.reload()">再来一次吧</button>
    `;

    endgameE1.style.display = 'flex';
}

addWordToDom();


function getRandomWord() {
    return words[Math.floor(Math.random() * words.length)];
}

//输出单词到DOM
function addWordToDom() {
    randomWord = getRandomWord();
    word.innerHTML = randomWord;
}

addWordToDom();

//事件监听器
text.addEventListener('input',function(e) {
    const insertedText = e.target.value;
    
    if(insertedText === randomWord) {
        addWordToDom();
        updateScore();

        //清除输入框
        e.target.value = '';

        if (difficulty === randomWord) {
            addWordToDom();
            updateScore();

            //清楚输入框
            e.target.value = '';

            if (difficulty === 'hard') {
                time += 2;
            } else if (difficulty === 'medium') {
                time += 3;
            } else {
                time += 5;
            }
     }

        updateTime();
    }
})

//设置按钮点击
settingBtn.addEventListener('click', function() {
    settings.classList.toggle('hide');
});

//设置下拉选项
settingsForm.addEventListener('change', function(e) {
    difficulty = e.target.value;
    localStorage.setItem('difficulty', difficulty);
})